package com.hslxy.niukewang.controller;

import com.hslxy.niukewang.component.Page;
import com.hslxy.niukewang.entity.Comment;
import com.hslxy.niukewang.entity.DiscussPost;
import com.hslxy.niukewang.entity.Event;
import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.event.EventProducer;
import com.hslxy.niukewang.service.CommentService;
import com.hslxy.niukewang.service.DiscussPostService;
import com.hslxy.niukewang.service.LikeService;
import com.hslxy.niukewang.service.UserService;
import com.hslxy.niukewang.util.CommunityUtil;
import com.hslxy.niukewang.util.Constant;
import com.hslxy.niukewang.util.HostHolder;
import com.hslxy.niukewang.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements Constant {
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String discussPost(String title, String content){
        User user = hostHolder.getUsers();
        if(user == null){
            return CommunityUtil.getJSONString(403, "你还没登录");
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);
//        触发事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());
        eventProducer.fireEvent(event);

//        计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, discussPost.getId());

        return CommunityUtil.getJSONString(0, "发布成功");
    }
    @RequestMapping(path = "/detail/{id}", method = RequestMethod.GET)
    public String discussPost(@PathVariable("id")int id, Model model, Page page){
        DiscussPost discussPost = discussPostService.findDiscussPost(id);
        User user = userService.findUserById(discussPost.getUserId());
        if(discussPost != null && user != null){
            model.addAttribute("discussPost", discussPost);
            model.addAttribute("user", user);
        }

//        点赞数量
        Long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, id);
        model.addAttribute("likeCount", likeCount);
//        点赞状态
        int likeStatus = hostHolder.getUsers() == null ? 0:likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_POST, id);
        model.addAttribute("likeStatus", likeStatus);

        page.setLimit(5);
        page.setPath("/discuss/detail/" + id);
        page.setRows(discussPost.getCommentCount());
//        得到这个帖子的评论
        List<Comment> comments =
                commentService.selectCommentsByEntity(ENTITY_TYPE_POST, discussPost.getId(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> commentsMapList = new ArrayList<>();
        if(comments != null){
            for (Comment comment :
                    comments) {
                Map<String, Object> commentsMap = new HashMap<>();
                commentsMap.put("comment", comment);
                commentsMap.put("user", userService.findUserById(comment.getUserId()));

                //        点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentsMap.put("likeCount", likeCount);
                //        点赞状态
                likeStatus = hostHolder.getUsers() == null ? 0:likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentsMap.put("likeStatus", likeStatus);

//                处理评论的评论
                List<Comment> commentscomment =
                        commentService.selectCommentsByEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                List<Map<String, Object>> commentscommentMapList = new ArrayList<>();
                if(commentscomment != null)
                    for (Comment cosco :
                            commentscomment) {
                        Map<String, Object> commentscommentMap = new HashMap<>();
                        commentscommentMap.put("comment", cosco);
                        commentscommentMap.put("user", userService.findUserById(cosco.getUserId()));
                        User targetUser = cosco.getTargetId() == 0 ? null : userService.findUserById(cosco.getTargetId());
                        commentscommentMap.put("targetUser", targetUser);

                        //        点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, cosco.getId());
                        commentscommentMap.put("likeCount", likeCount);
                        //        点赞状态
                        likeStatus = hostHolder.getUsers() == null ? 0:likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_COMMENT, cosco.getId());
                        commentscommentMap.put("likeStatus", likeStatus);

                        commentscommentMapList.add(commentscommentMap);
                    }
                commentsMap.put("commentscomment", commentscommentMapList);
                commentsMap.put("commentscommentCount", commentService.selectCountByEntity(ENTITY_TYPE_COMMENT, comment.getId()));
                commentsMapList.add(commentsMap);
            }
        }
        model.addAttribute("comments", commentsMapList);
        return "/site/discuss-detail";
    }

//    置顶
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(id, 1);
        //        触发事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUsers().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJSONString(0);
    }
//    加精

    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id){
        discussPostService.updateStatus(id, 1);
        //        触发事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUsers().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        //        计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, id);

        return CommunityUtil.getJSONString(0);
    }

//    删除
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id){
        discussPostService.updateStatus(id, 2);
        //        触发事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUsers().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJSONString(0);
    }


}
